/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.PrePurchaseRequest;
import me.zhengjie.modules.system.domain.PrePurchaseRequestDetail;
import me.zhengjie.modules.system.domain.vo.PrePurchaseRequestDetailAuditVo;
import me.zhengjie.modules.system.service.PrePurchaseRequestDetailService;
import me.zhengjie.modules.system.service.PrePurchaseRequestService;
import me.zhengjie.modules.system.service.dto.PrePurchaseRequestDetailQueryCriteria;
import me.zhengjie.modules.system.service.dto.PrePurchaseRequestDto;
import me.zhengjie.modules.system.service.dto.PrePurchaseRequestQueryCriteria;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import me.zhengjie.utils.PageResult;
import me.zhengjie.modules.system.service.dto.PrePurchaseRequestDetailDto;
import org.springframework.web.multipart.MultipartFile;

/**
* @website https://eladmin.vip
* @author 李忠臻
* @date 2024-03-08
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "请购单明细管理")
@RequestMapping("/api/prePurchaseRequestDetail")
public class PrePurchaseRequestDetailController {

    private final PrePurchaseRequestDetailService prePurchaseRequestDetailService;

    private final PrePurchaseRequestService prePurchaseRequestService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('prePurchaseRequestDetail:list')")
    public void exportPrePurchaseRequestDetail(HttpServletResponse response, PrePurchaseRequestDetailQueryCriteria criteria) throws IOException {

        if (CollectionUtil.isNotEmpty(criteria.getPrePurchaseRequestId()) ) {
            PrePurchaseRequestQueryCriteria prePurchaseRequestQueryCriteria = new PrePurchaseRequestQueryCriteria();
            prePurchaseRequestQueryCriteria.setId(criteria.getPrePurchaseRequestId());
            List<PrePurchaseRequestDto> prePurchaseRequestDtoList = prePurchaseRequestService.queryAll(prePurchaseRequestQueryCriteria);

            Map<String, List<PrePurchaseRequestDto>> supplierGroupMap = prePurchaseRequestDtoList.stream().
                    collect(Collectors.groupingBy(PrePurchaseRequestDto::getPurchaseAttribute));
            if (supplierGroupMap.size() > 1) {
                throw new BadRequestException("需要选择相同的采购性质，请重新选择");
            }

            if (supplierGroupMap.containsKey("直发") && prePurchaseRequestDtoList.size() > 1) {
                throw new BadRequestException("直发只能单条导出，请重新选择");
            }
        }

        prePurchaseRequestDetailService.download(prePurchaseRequestDetailService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询请购单明细")
    @ApiOperation("查询请购单明细")
//    @PreAuthorize("@el.check('prePurchaseRequestDetail:list')")
    public ResponseEntity<PageResult<PrePurchaseRequestDetailDto>> queryPrePurchaseRequestDetail(PrePurchaseRequestDetailQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(prePurchaseRequestDetailService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增请购单明细")
    @ApiOperation("新增请购单明细")
    @PreAuthorize("@el.check('prePurchaseRequestDetail:add')")
    public ResponseEntity<Object> createPrePurchaseRequestDetail(@Validated @RequestBody PrePurchaseRequestDetail resources){
        prePurchaseRequestDetailService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改请购单明细")
    @ApiOperation("修改请购单明细")
    @PreAuthorize("@el.check('prePurchaseRequestDetail:edit')")
    public ResponseEntity<Object> updatePrePurchaseRequestDetail(@Validated @RequestBody PrePurchaseRequestDetail resources){
        prePurchaseRequestDetailService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除请购单明细")
    @ApiOperation("删除请购单明细")
    @PreAuthorize("@el.check('prePurchaseRequestDetail:del')")
    public ResponseEntity<Object> deletePrePurchaseRequestDetail(@RequestBody Long[] ids) {
        prePurchaseRequestDetailService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/list/{id}")
    @Log("请购单申请明细")
    @ApiOperation("请购单申请明细")
//    @PreAuthorize("@el.check('purchaseRequest:list')")
    public ResponseEntity<Object> listPurchaseRequestDetail(@PathVariable Long id) {

        return new ResponseEntity<>(prePurchaseRequestDetailService.queryByPrePurchaseRequestId(id), HttpStatus.OK);
    }

    @PostMapping(value = "/pass")
    @Log("推送请购单明细")
    @ApiOperation("推送请购单明细")
    @PreAuthorize("@el.check('prePurchaseRequestDetail:add')")
    public ResponseEntity<Object> passPrePurchaseRequestDetail(@RequestBody PrePurchaseRequestDetailAuditVo prePurchaseRequestDetailAuditVo) {
        prePurchaseRequestDetailService.pass(prePurchaseRequestDetailAuditVo);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping(value = "/upload")
    @ApiOperation("上传文件")
    @PreAuthorize("@el.check('prePurchaseRequestDetail:add')")
    public ResponseEntity<Object> uploadPurchaseRequest(@RequestParam("file") MultipartFile file){
//        localStorageService.create(name, file);
//        PurchaseRequest resources = new PurchaseRequest();

        prePurchaseRequestDetailService.upload(file);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
}